package controller;

import com.alibaba.fastjson.JSON;
import pojo.User;
import service.Impl.UserServiceImpl;
import service.UserService;
import servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/user")
public class UserController extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    public void doDrawCode(HttpServletRequest request,HttpServletResponse response){
        userService.drawCode(request,response);
    }

    public void doLogin(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException, SQLException {
        String login = userService.login(request, response);
        response.getWriter().write(login);
    }

    public void doLoginOut(HttpServletRequest request,HttpServletResponse response) throws IOException {
        userService.loginOut(request, response);
        response.sendRedirect("welcome.html");
    }

    public void doResetPassword(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, SQLException {
        boolean resetPassword = userService.resetPassword(request, response);
        String code;
        if(resetPassword){
            code = "1";
        }else{
            code = "-1";
        }
        response.getWriter().write(code);
    }

    public void getUser(HttpServletRequest request,HttpServletResponse response) throws IOException {


        User user = (User) request.getSession().getAttribute("user");
        String userJSONStr = JSON.toJSONString(user);

        String role = (String) request.getSession().getAttribute("role");

        String jsonStr = "{'role':'" + role + "','user':" + userJSONStr + "}";

        response.getWriter().write(jsonStr);
    }


}